// 2025/5/23
// 体育课测验（二）

class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     * 
     * @param numProject int整型 
     * @param groups int整型vector<vector<>> 
     * @return int整型vector
     */
    vector<int> findOrder(int numProject, vector<vector<int> >& groups) {
        // write code here
        vector<vector<int>> adjlist(numProject);
        vector<int> precount(numProject, 0);
        for(auto& group : groups)
        {
            adjlist[group[1]].emplace_back(group[0]);
            ++precount[group[0]];
        }
        queue<int> ready;
        vector<int> ans;
        for(int i = 0; i < numProject; i++)
        {
            if(precount[i] == 0)
                ready.emplace(i);
        }

        while(!ready.empty())
        {
            int cur = ready.front();
            ready.pop();
            ans.emplace_back(cur);
            for(auto& num : adjlist[cur])
            {
                --precount[num];
                if(precount[num] == 0)
                    ready.emplace(num);
            }
        }
        return ans.size() == numProject ? ans : (vector<int>){};
    }
};